/* $RCSFile: PrivateDocFeeder.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.EMailing/PageModules/DownloadSession/PrivateDocFeeder.ascx.cs $
 * $log$
 * Revision 23 2010/08/09 11:12:45  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 10 2010/08/09 10:13:18  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Data;
using System.Drawing;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.Globalization;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;

using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;

using AddonNice.CRMWrapper;

using AddonNice.CRMEMailing;
using AddonNice.CRMEMailing.Settings.UI.WebControls;
using AddonNice.Settings.CRMEMailing;
using AddonNice.CRMWrapper.CRMEMailing;

using Trace2    =   System.Diagnostics.Trace;
using System.Text;

namespace AddonNice.PageModules.DownloadSession
{
    /// <summary>
    /// Initializer class for PrivateDocFeeder 
    /// </summary>
    public class PrivateDocFeederSI : PrivateDocFeeder0SI
    {
        public PrivateDocFeederSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base(bSettings,pm)
        {
            if ( PrivateDocFeederTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDocFeederSI Ctor BEG.",PrivateDocFeederTrace.Sw.Info);
            InitSettings(bSettings,pm);
            if ( PrivateDocFeederTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDocFeederSI Ctor END.",PrivateDocFeederTrace.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( PrivateDocFeederTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDocFeederSI InitSettings BEG.",PrivateDocFeederTrace.Sw.Info);
            
            base.InitSettings(bSettings,pm);

			
            if ( PrivateDocFeederTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDocFeederSI InitSettings END.",PrivateDocFeederTrace.Sw.Info);
        }
 
    }

    /// <summary>
    /// From a folder, a campaign, a marketinglist read documents in a folder and generates privateDocuments entities related to current campaign
    /// Also fill a table to accelerate the sending of bulk emails referencing privatedocuments, as we need to send the private document id for each mail we will access them with the the sessionid, the listuserid
    /// </summary>
    public partial class PrivateDocFeeder : PrivateDocFeeder0
    {

        #region General implementation
        
        public override Guid GuidID
        {
            get
            {
                return new Guid(AStr.PrivateDocFeederGuid);
            }
        }
        #endregion General implementation

        
        public PrivateDocFeeder()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDocFeeder Ctor Called.",ModuleTraceSwitch.Sw.Info);
            // Validators : name Ok
            ValidationGroup                     =   "Main";

        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                 =   "PRIVATEDOCFEEDER";
                return extgrp;
            }
		}
 
        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new PrivateDocFeederSI(bSettings,this);
        }

    
         protected void Page_Load(object sender, EventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose | PrivateDocFeederTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PrivateDocFeeder Page_Load isPostBack: {0}",IsPostBack),(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:PrivateDocFeederTrace.Sw.Info);
            const string fmt                        =   "realPostBack('{0}', ''); return false;";
            updateBtn.OnClientClick                 =   string.Format(fmt, updateBtn.UniqueID);

            if (!IsPostBack)
            {
                TbFileExt.Text                      =   Settings[AStr.DefaultFileExt].ToString();
            }
        }

        void RadGrid1_NeedDataSource(object source,Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            
            if ( string.IsNullOrEmpty(CbDownloadSession.SelectedValue) )
            {
                lblMsg.Text             =   "You must select a DownloadSession";
                if (PrivateDocFeederTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( "[V]PrivateDocFeeder PrivateDocFeeder_ADNUpdateModule no DownloadSession",PrivateDocFeederTrace.Sw.Info);
                return;
            }
            // Update or Add new entity to Crm
            try
            {
                Guid DwnSessionId       =   new Guid(CbDownloadSession.SelectedValue);
                if (PrivateDocFeederTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PrivateDocFeeder PrivateDocFeeder_ADNUpdateModule  DwnSessionId: {0}", DwnSessionId),PrivateDocFeederTrace.Sw.Info);
                FillWithCampaign(DwnSessionId,filenameFmt.FmtName,false);
            }
            catch (Exception ex)
            {
                if (PrivateDocFeederTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]PrivateDocFeeder PrivateDocFeeder_ADNUpdateModule  ex: {0}", ex),PrivateDocFeederTrace.Sw.Info);
                throw;
            }
        }

        void FillWithCampaign(Guid SessionId,filenameFmt fft,bool associateFile)
        {
            if (PrivateDocFeederTrace.Sw.TraceVerbose)
                Trace2.WriteLine(  string.Format(CultureInfo.InvariantCulture,"[V]PrivateDocFeeder FillWithCampaign BEG SessionId: {0}, fft: {1} .",SessionId,fft),PrivateDocFeederTrace.Sw.Info);
            ADNDynDownloadSession dynSess           =   DynEntity.GetFromCache<ADNDynDownloadSession>(AStr.adndownloadsession,Wrapper,ResetWrapper,SessionId);
            Guid campaignid                         =   dynSess.campaignid;
            Guid listid                             =   dynSess.listid;
            if (PrivateDocFeederTrace.Sw.TraceVerbose)
                Trace2.WriteLine(  string.Format(CultureInfo.InvariantCulture,"[V]PrivateDocFeeder FillWithCampaign campaignid: {0}, listid: {1} .",campaignid,listid),PrivateDocFeederTrace.Sw.Info);
            if (( campaignid == Guid.Empty ) && ( listid == Guid.Empty ) )
            {
                lblMsg.Text                         =   "You must select a DownloadSession with a marketing campaign or a marketing list associated";
                return;
            }
            string title                            =   dynSess.adntitle;
            string prefix                           =   dynSess.adnprefix;
            string path                             =   Server.MapPath(ImportFileName.Text);
            if (PrivateDocFeederTrace.Sw.TraceVerbose)
                Trace2.WriteLine(  string.Format(CultureInfo.InvariantCulture,"[V]PrivateDocFeeder FillWithCampaign title: {0}, prefix: {1}, path: {2}.",title,prefix,path),PrivateDocFeederTrace.Sw.Info);
            if ( campaignid != Guid.Empty )
            {
                ADNDynCampaign dynCamp              =   DynEntity.GetFromCache<ADNDynCampaign>(CrmStr.campaign,Wrapper,ResetWrapper,campaignid);
                SortedList<Guid,ADNDynList> lists   =   dynCamp.ReadAllList(ResetWrapper,string.Empty);
                if (PrivateDocFeederTrace.Sw.TraceVerbose)
                    Trace2.WriteLine(  string.Format(CultureInfo.InvariantCulture,"[V]PrivateDocFeeder FillWithCampaign lists.Count: {0}.",lists.Count),PrivateDocFeederTrace.Sw.Info);
                if ( lists.Count == 0 )
                {
                    lblMsg.Text                     =   "The related campaign has no marketing lists";
                    return;
                }
                foreach ( Guid lstid in lists.Keys )
                {
                    FillFromFolderWithList(SessionId,lstid,lists[lstid],title,prefix,path,fft,associateFile);
                }
            }
            else
            {
                ADNDynList dynList              =   DynEntity.GetFromCache<ADNDynList>(CrmStr.list,Wrapper,ResetWrapper,listid);
                FillFromFolderWithList(SessionId,listid,dynList,title,prefix,path,fft,associateFile);
            }
        }

        void FillFromFolderWithList(Guid SessionId,Guid listid,ADNDynList dynList,string title,string prefix,string path,filenameFmt fft,bool associateFile)
        {
            if (PrivateDocFeederTrace.Sw.TraceVerbose)
                Trace2.WriteLine(  string.Format(CultureInfo.InvariantCulture,"[V]PrivateDocFeeder FillFromFolderWithList BEG SessionId: {0}, listid: {1}.",SessionId,listid),PrivateDocFeederTrace.Sw.Info);
            List<ADNDynCustomer> lst                =   dynList.GetMembers(ResetWrapper);
            ADNDynList.ListType ltype               =   dynList.MemberType;
            StringBuilder sb                        =   new StringBuilder();
            string ext                              =   TbFileExt.Text;
            if ( string.IsNullOrEmpty(ext))
                ext                                 =   "txt";
            foreach ( ADNDynCustomer dynCust in lst )
            {
                // format the filename
                Guid custId                         =   dynCust.PrimaryKeyGuidValue;
                string filename                     =   string.Empty;
                switch ( fft )
                {
                    case filenameFmt.fmtGuid:
                    filename                        =   string.Format("{0}-{1}-{2}.{3}",new object[]{prefix,dynCust.SchemaName,custId,ext});
                    break;
                    case filenameFmt.FmtName:
                    filename                        =   string.Format("{0}-{1}-{2}.{3}",new object[]{prefix,dynCust.SchemaName,dynCust.PrimaryFieldStringValue,ext});
                    break;
                }

                string path2                        =   System.IO.Path.Combine(path,filename);
                bool fileExists                     =   File.Exists(path2) ;
                if (PrivateDocFeederTrace.Sw.TraceVerbose)
                    Trace2.WriteLine(  string.Format(CultureInfo.InvariantCulture,"[V]PrivateDocFeeder FillFromFolderWithList filename: {0}, path2: {1}, fileExists: {2}.",filename,path2,fileExists),PrivateDocFeederTrace.Sw.Info);
                bool created                        =   false;
                if ( fileExists )
                {
                    InternalQueryExpression qe      =   new InternalQueryExpression();
                    qe.ColumnSet                    =   new InternalAllColumns();
                    qe.EntityName                   =   AStr.adnprivatedocument;
                    qe.Criteria                     =   new InternalFilterExpression();
                    InternalConditionExpression ce  =   new InternalConditionExpression();
                    switch (ltype)
                    {
                        case ADNDynList.ListType.Account:
                        ce.AttributeName            =   AStr.adnaccountid;
                        break;
                        case ADNDynList.ListType.Contact:
                        ce.AttributeName            =   AStr.adncontactid;
                        break;
                        case ADNDynList.ListType.Lead:
                        ce.AttributeName            =   AStr.adnleadid;
                        break;
                    }
                    ce.Operator                     =    InternalConditionOperator.Equal;
                    ce.Values                       =   new string[] { custId.ToString()};
                    InternalConditionExpression ce2 =   new InternalConditionExpression();
                    ce2.AttributeName               =   AStr.adndownloadsessionid;
                    ce2.Operator                    =    InternalConditionOperator.Equal;
                    ce2.Values                      =   new string[] { SessionId.ToString()};
                    qe.Criteria.Conditions          =   new InternalConditionExpression[]{ce,ce2};
                    int count                       =   0;
                    ADNDynPrivateDocument priv      =   Wrapper.Util.FindEntityByQuery<ADNDynPrivateDocument>(AStr.adnprivatedocument,qe,ResetWrapper,ref count,true,null);
                    if (PrivateDocFeederTrace.Sw.TraceVerbose)
                        Trace2.WriteLine(  string.Format(CultureInfo.InvariantCulture,"[V]PrivateDocFeeder FillFromFolderWithList filename: {0}, ADNDynPrivateDocument null: {1}.",filename,(priv == null)),PrivateDocFeederTrace.Sw.Info);
                    if ( priv == null )
                    {
                        priv                        =   new ADNDynPrivateDocument(ResetWrapper,filename);
                        priv.adntitle               =   title;
                        priv.adnfileurl             =   filename;
                        switch (ltype)
                        {
                            case ADNDynList.ListType.Account:
                            priv.adnaccountid       =   custId;
                            break;
                            case ADNDynList.ListType.Contact:
                            priv.adncontactid       =   custId;
                            break;
                            case ADNDynList.ListType.Lead:
                            priv.adnleadid          =   custId;
                            break;
                        }
                        priv.adncategory            =   1;
                        priv.adnfileurl             =   path2;
                        priv.adndownloadsessionid   =   SessionId;
                        priv.adndownloadcount       =   0;
                        priv.Create();
                        created                     =   true;
                    }
                    else if ( priv.adnexternalid == 0 )
                        created                     =   true;
                    bool loaded                     =   LoadFile(priv,path2,title,filename,created);
                    sb.AppendFormat("{0} loaded : {1}<br />",path2,loaded);
                }
            }
            LblFiles.Text                           =   sb.ToString();
        }

        void PrivateDocFeeder_ADNUpdateModule(object sender, ModuleEventArgs e)
        {
            if (PrivateDocFeederTrace.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]PrivateDocFeeder PrivateDocFeeder_ADNUpdateModule BEG.",PrivateDocFeederTrace.Sw.Info);
            // Should Email contain values
            if (!Page.IsValid)
            {
                if (PrivateDocFeederTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( "[V]PrivateDocFeeder PrivateDocFeeder_ADNUpdateModule : Page not valid",PrivateDocFeederTrace.Sw.Info);
                return;
            }

            if ( string.IsNullOrEmpty(CbDownloadSession.SelectedValue) )
            {
                lblMsg.Text             =   "You must select a DownloadSession";
                if (PrivateDocFeederTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( "[V]PrivateDocFeeder PrivateDocFeeder_ADNUpdateModule no DownloadSession",PrivateDocFeederTrace.Sw.Info);
                return;
            }

            // Update or Add new entity to Crm
            try
            {
                Guid DwnSessionId       =   new Guid(CbDownloadSession.SelectedValue);
                if (PrivateDocFeederTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PrivateDocFeeder PrivateDocFeeder_ADNUpdateModule  DwnSessionId: {0}", DwnSessionId),PrivateDocFeederTrace.Sw.Info);
                FillWithCampaign(DwnSessionId,filenameFmt.FmtName,true);
            }
            catch (Exception ex)
            {
                if (PrivateDocFeederTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]PrivateDocFeeder PrivateDocFeeder_ADNUpdateModule  ex: {0}", ex),PrivateDocFeederTrace.Sw.Info);
                throw;
            }
        }

        #region Std overrides

        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            updateBtn.SkinID        =   "Update_" + Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            BtnChooseFile.SkinID    =   "Open_"+ Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
        }

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            Load                                        +=  new System.EventHandler(Page_Load);
            CbDownloadSession.WebServiceSettings.Method =   "GetDownloadSessions";
            CbDownloadSession.WebServiceSettings.Path   =   "/Services/XrmEmailing.asmx";

            CbDownloadSession.WebServiceMethod          =   "GetDownloadSessions";
            CbDownloadSession.WebServicePath            =   "/Services/XrmEmailing.asmx";
            ADNUpdateModule                             +=  new PortalModuleEventHandler(PrivateDocFeeder_ADNUpdateModule);

            RadGrid1.NeedDataSource += new Telerik.Web.UI.GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);
        }

        #endregion Std overrides
    }
}